package org.derusse.cycle.database;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.BaseColumns;

public class TrackTable implements BaseColumns
{

	public static final class Structure implements BaseColumns
	{
		// This class cannot be instantiated
		private Structure()
		{
		}

		public static final String TABLE_NAME = "track";

		public static final String START = "start";
		public static final String STOP = "end";
		public static final String MAX = "max";
		public static final String AVG = "avg";
		public static final String DISTANCE = "distance";
	}

	public static void onCreate(SQLiteDatabase db)
	{
		db.execSQL("CREATE TABLE " + Structure.TABLE_NAME + " (" + Structure._ID + " INTEGER PRIMARY KEY," + Structure.START + " LONG," + Structure.STOP + " LONG," + Structure.MAX + " FLOAT,"
				+ Structure.AVG + " FLOAT," + Structure.DISTANCE + " FLOAT);");
	}

	public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	{
		if (oldVersion < 5)
		{
			db.execSQL("DROP TABLE IF EXISTS " + Structure.TABLE_NAME);
			onCreate(db);
		}
	}

	public static long Insert(SQLiteDatabase db, long startDate)
	{
		ContentValues values = new ContentValues();
		values.put(Structure.START, startDate);
		values.put(Structure.STOP, startDate);
		values.put(Structure.MAX, 0);
		values.put(Structure.AVG, 0);
		values.put(Structure.DISTANCE, 0);

		return db.insert(Structure.TABLE_NAME, null, values);
	}

	public static void Update(SQLiteDatabase db, long id, long stopDate, double max, double avg, double distance)
	{
		ContentValues values = new ContentValues();
		values.put(Structure.STOP, stopDate);
		values.put(Structure.MAX, max);
		values.put(Structure.AVG, avg);
		values.put(Structure.DISTANCE, distance);

		db.update(Structure.TABLE_NAME, values, Structure._ID + " = ?", new String[]
		{ String.valueOf(id) });
	}

	public static Cursor List(SQLiteDatabase db) {
		return db.query(Structure.TABLE_NAME, new String[] { Structure._ID,
				Structure.DISTANCE, Structure.AVG, Structure.START,
				Structure.STOP }, null, null, null, null, Structure.START
				+ " DESC");
	}
}
